import axios,{ AxiosInstance } from 'axios'

//设置请求超时重新请求的请求次数，请求的间隙
Object.assign(axios.defaults,{
    retry:4,
    retryDelay:1000
})

const service:AxiosInstance = axios.create({
    baseURL:import.meta.env.VITE_API_BASEURL,
    timeout:8000,
    withCredentials:true
})

// request interceptor
service.interceptors.request.use(
    request => {
      return request
    },
    err => {
      // do something with request error
      console.log(err) // for debug
      return Promise.reject(err)
    }
  )
  
// response interceptor
service.interceptors.response.use(
    response => {
      const res = response.data
      if (res.code !== 200) {
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        return res
      }
    },
    err => {
      console.log('err' + err) // for debug
      //https://github.com/axios/axios/issues/164 超时后重新请求
      let config = err.config;
  
      if(!config || !config.retry) return Promise.reject(err);
  
      config.__retryCount = config.__retryCount || 0;
  
      if(config.__retryCount >= config.retry) {
        return Promise.reject(err);
      }
  
      config.__retryCount += 1;
  
      let backoff = new Promise(function(resolve) {
        setTimeout(function() {
          resolve(void(0));
        }, config.retryDelay || 1);
      });
      return backoff.then(function() {
        return service(config);
      });
    }
  )
  
  export default service

